package com.seo.service.user.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seo.mapper.user.ConfigMapper;
import com.seo.mapper.user.UserDomainMapper;
import com.seo.mapper.user.UserMapper;
import com.seo.pojo.ReturnBody;
import com.seo.service.user.sdk.UserDomainService;
import com.seo.utils.ClientConst;
import com.seo.utils.DomainUtil;
import com.seo.utils.Jurisdiction;
import com.seo.utils.PatternTool;

import cn.hutool.core.util.ReUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("userDomainService")
public class UserDomainServiceImpl implements UserDomainService {

	@Autowired
	private UserDomainMapper userDomainMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ConfigMapper configMapper;

	@Override
	public ReturnBody getUserDomain(int userId) {
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = userMapper.getUserById(userId);

		log.info("返回用户域名列表");
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		List<Map<String, Object>> userDomainList = userDomainMapper.getUserDomainByUserId(params);
		String port = configMapper.getConfig("seo-port");
		if (!"80".equals(port)) {
			rb.put("port", port);
		}

		int parentId = (int) user.get("parentId");
		if (parentId == 0) {
			String userName = (String) user.get("userName");
			String domain = getDefaultDomain(userName);
			rb.put("domain", domain);
		} else {
			userDomainList.addAll(0, getBindingDomain(parentId));
		}
		rb.put("userDomainList", userDomainList);
		return rb.success();
	}

	@Override
	public String getDefaultDomain() {
		String userName = Jurisdiction.getT("userName", String.class, ClientConst.SESSION_USER);
		String domain = userName + "." + configMapper.getConfig("domain");
		return domain;
	}

	@Override
	public List<Map<String, Object>> getBindingDomain(int parentId) {
		Map<String, Object> params = new HashMap<>();
		params.put("userId", parentId);
		params.put("state", "01");
		List<Map<String, Object>> userDomainList = userDomainMapper.getUserDomainByUserId(params);
		return userDomainList;
	}

	@Override
	public String getDefaultDomain(String userName) {
		String domain = userName + "." + configMapper.getConfig("domain");
		return domain;
	}

	@Override
	public String getSeoDomain() {
		String domain = configMapper.getConfig("domain");
		String port = configMapper.getConfig("seo-port");
		if (!"80".equals(port)) {
			domain = domain + ":" + port;
		}
		return domain;
	}

	@Override
	public String getSysDefaultRegister() {
		String registerDomain = configMapper.getConfig("register_domain");
		String port = configMapper.getConfig("seo-port");
		if (!"80".equals(port)) {
			registerDomain = registerDomain + ":" + port;
		}
		return registerDomain + "/noExists/register";
	}

	@Override
	public ReturnBody verify(String domain) {
		ReturnBody body = ReturnBody.init();
		domain = StringUtils.trim(domain);

		if (StringUtils.isEmpty(domain)) {
			log.error("域名不能为空");
			return body.error("域名不能为空");
		}

		if (domain.length() > 100) {
			log.error("域名过长");
			return body.error("域名过长");
		}

		if (!ReUtil.contains(PatternTool.DOMAIN, domain)) {
			log.error("请输入合法的域名");
			return body.error("请输入合法的域名");
		}

		String userName = Jurisdiction.getT("userName", String.class, ClientConst.SESSION_USER);
		log.info("用户名-[{}]", userName);
		String recordValue = SecureUtil.md5(userName);
		if (DomainUtil.checkTxt("jinfaren-verify." + domain, recordValue)) {
			return body.success();
		} else {
			return body.error("校验失败");
		}
	}

	@Override
	public ReturnBody verify(String userName, String domain) {
		ReturnBody body = ReturnBody.init();
		domain = StringUtils.trim(domain);

		if (StringUtils.isEmpty(domain)) {
			log.error("域名不能为空");
			return body.error("域名不能为空");
		}

		if (domain.length() > 100) {
			log.error("域名过长");
			return body.error("域名过长");
		}

		if (!ReUtil.contains(PatternTool.DOMAIN, domain)) {
			log.error("请输入合法的域名");
			return body.error("请输入合法的域名");
		}

		log.info("用户名-[{}]", userName);
		String recordValue = SecureUtil.md5(userName);
		if (DomainUtil.checkTxt("jinfaren-verify." + domain, recordValue)) {
			return body.success();
		} else {
			return body.error("校验失败");
		}
	}

	@Override
	public ReturnBody save(String hostRecord, String domain) {
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		return save(userId, hostRecord, domain);
	}

	@Override
	public ReturnBody save(int userId, String hostRecord, String domain) {
		ReturnBody body = ReturnBody.init();
		try {
			hostRecord = StringUtils.trim(hostRecord);

			if (StringUtils.isEmpty(hostRecord)) {
				log.error("域名主记录不能为空");
				return body.error("域名主记录不能为空");
			}

			if (hostRecord.length() > 100) {
				log.error("域名主记录过长");
				return body.error("域名主记录过长");
			}

			if (!ReUtil.contains(PatternTool.HOST_RECORD, hostRecord)) {
				log.error("请输入合法的域名主记录");
				return body.error("请输入合法的域名主记录");
			}
			domain = StringUtils.trim(domain);
			Map<String, Object> user = userMapper.getUserById(userId);
			String userName = (String) user.get("userName");
			body.run(verify(userName, domain));
			if (!body.isSuccess()) {
				return body;
			}

			String finalDomain = hostRecord + "." + domain;
			Map<String, Object> userDomain = userDomainMapper.getUserDomainByDomain(finalDomain);
			if (userDomain != null) {
				log.error("该域名已绑定");
				return body.error("该域名已绑定");
			}

			String recordValue = getDefaultDomain(userName);
			log.info("域名-[{}]-解析地址-[{}]", finalDomain, recordValue);
			if (DomainUtil.checkCname(finalDomain, recordValue)) {
				Map<String, Object> params = new HashMap<>();
				params.put("domain", finalDomain);
				params.put("userId", userId);
				int num = userDomainMapper.saveUserDomain(params);
				if (num == 0) {
					log.error("保存失败");
					return body.error("域名绑定失败");
				}
				return body.success();
			} else {
				log.error("检测失败");
				return body.error("域名CNAME解析失败");
			}

		} catch (Exception e) {
			log.error("异常-[{}]", e);
			return body.rollback("绑定失败");
		} finally {
			body.result();
		}
	}

	@Override
	public ReturnBody updateUserDomain(Map<String, Object> params) {
		ReturnBody body = ReturnBody.init();
		int num = userDomainMapper.updateUserDomain(params);
		if (num == 0) {
			return body.error("保存失败");
		}

		return body.success();
	}

	@Override
	public ReturnBody deleteUserDomain(int id) {
		ReturnBody body = ReturnBody.init();
		int num = userDomainMapper.deleteUserDomain(id);
		if (num == 0) {
			return body.error("删除失败");
		}

		return body.success();
	}

}
